package com.peach.stock.service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.peach.stock.common.MapValueComparator;
import com.peach.stock.domain.Stock11Model;
import com.peach.stock.domain.Stock12Model;
import com.peach.stock.domain.StockModel;
import com.peach.stock.mapper.StockMapper;

/**
 * 分析
 * 量增价平，转阳信号;量增价升，买入信号;量平价升，持续买入;量减价升，继续持有;
 * 量减价平，警戒信号;量减价跌，卖出信号;量平价跌，继续卖出;量增价跌，勿卖观望
 * @author robin
 *
 */
@Service
public class AnalysisService {

	private static final Logger log = LoggerFactory.getLogger(AnalysisService.class);
	
	@Autowired
	StockMapper mapper;

	/**
	 * 获取超跌股(n个交易日累计跌幅前10)
	 * 
	 * @param n
	 */
	public String getCD(int n) {
		List<String> lst2 = mapper.select21limit(n + 1);
		String str = lst2.get(lst2.size() - 1);
		String end = lst2.get(0);
		
		StringBuffer result = new StringBuffer(String.valueOf(n));
		result.append("个交易日累计跌幅前10:\r\n");
//		select dm, sum(pctChg) as chg from stck11 where rq > '2020-11-02' group by dm order by chg
		List<Map<String, Object>> lst = mapper.countCD(str);
		for (Map<String, Object> m : lst)
		{
			String dm = m.get("dm").toString();
			Map<String, String> stock = mapper.select01(dm);
			result.append(dm);
			result.append(" ");
			result.append(stock.get("nm"));
			result.append(" ");
			result.append(stock.get("hy01"));
			result.append("\r\n");
			result.append(m.get("chg"));
			result.append("|");
			result.append(m.get("am"));
			result.append("\r\n");
		}
		
//		List<StockModel> lst = getDownTop(str, end);
//		for (StockModel sm : lst)
//		{
//			result.append(sm.getStock11().getDm());
//			result.append(" ");
//			result.append(sm.getPercent());
//			result.append(" ");
//			result.append(sm.getHynm());
//			result.append("\r\n");
//		}
		return result.toString();
	}

	public List<StockModel> getDownTop(String str, String end) {
//		select dm,sum(updown) as d from stck11 where rq>'2020-10-22' group by dm order by d;
		
		Map<String, BigDecimal> map = new TreeMap<String, BigDecimal>();
		
		List<String> lst1 = mapper.select01all();
		List<StockModel> result = new ArrayList<StockModel>();
		for (String dm : lst1) {
			Stock11Model strSM = mapper.select11(dm, str);
			Stock11Model endSM = mapper.select11(dm, end);
			if (strSM == null || endSM == null)
			{
				log.info("----" + dm);
				continue;
			}
//			log.info(dm + strSM.getPrice() + endSM.getPrice());

			BigDecimal bd1 = endSM.getClose().subtract(strSM.getPreclose());
			BigDecimal percent = bd1.divide(strSM.getPreclose(), 4, BigDecimal.ROUND_HALF_DOWN);

			StockModel sm = new StockModel();
			sm.setPercent(percent);
			sm.setStock11(endSM);
			result.add(sm);
			
			map.put(dm, percent.multiply(new BigDecimal(100)));
		}
		
		Collections.sort(result, new Comparator<StockModel>() {
			@Override
			public int compare(StockModel sm1, StockModel sm2) {
				// 排序
				return sm1.getPercent().compareTo(sm2.getPercent());
		    }
		});
		
		
		List<StockModel> r = addDetail(result.subList(0, 10));
//		savecsv(r, end);
		return r;
//		
//		// 排序
//		Map sort = sortMapByValue(map);
//		// 获取前10条
//		Set entries = sort.entrySet();
//		
//		Iterator it = entries.iterator();
//		
//		
//		for (int k = 0; it.hasNext(); k++) {
//			Map.Entry entry = (Map.Entry) it.next();
//			String dm = (String) entry.getKey();
//			String value = entry.getValue().toString();
//			if (k < 10)
//			{
////				log.info("key:" + dm + "    value:" + value);
//				StockModel sm = getStockModel(dm, end);
//				sm.setValue1(value);				
//				log.info(sm.toString());
//				result.add(sm);
//			}
//			else
//			{
//				map.remove(dm);
//			}
//		}
////		savecsv(result, end);
//		return result;
	}
	
	public List<StockModel> addDetail(List<StockModel> lst)
	{
		List<StockModel> result = new ArrayList<StockModel>();
		for (StockModel sm : lst)
		{
			String dm = sm.getStock11().getDm();
			Map<String, String> map = mapper.select01(dm);
			sm.setNm(map.get("nm"));
			sm.setHynm(map.get("hy01"));
//			sm.setLst(mapper.select12(dm));
			log.info(sm.toString());
			result.add(sm);
		}
		return result;
	}
	
	/**
	 * 个股详情
	 * @param dm
	 * @return
	 */
	public String getStockDetail(String dm)
	{
		Stock11Model stock11 = mapper.getone11(dm);
		if (stock11 != null)
		{
			stock11.getRq();
			Map<String, String> map = mapper.select01(dm);
			
		}
		
		
		return "";
	}
	
	public StockModel getStockModel(String dm)
	{
		List<String> lst2 = mapper.select21limit(1);
		String end = lst2.get(0);
		return getStockModel(dm, end);
	}
	
	public StockModel getStockModel(String dm, String rq)
	{
		Map<String, String> map = mapper.select01(dm);
		if (map == null)
		{
			return null;
		}
		StockModel sm = new StockModel();
		sm.setNm(map.get("nm"));
		sm.setHynm(map.get("hy01"));
//		sm.setNm(mapper.select01(dm));
//		sm.setHynm(mapper.select02hynm(dm));
		sm.setStock11(mapper.select11(dm, rq));
//		sm.setLst(mapper.select12(dm));
		return sm;
	}
	
	public String reportWeek()
	{
//		String result = "本周上证收盘%s，深证收盘%s；两市共成交%s万亿，较上周%s；总市值%s，较上周%s。"
//				+ "累计下跌幅度最大的前10股为%s";
		String result = "本周收盘上证指数%s，深证成指%s；";
		
		List<String> lst2 = mapper.select21limit(10);
		String str = lst2.get(lst2.size() - 1);
		String end = lst2.get(0);
		log.info(str);
		log.info(end);
		
		Map map = mapper.select21(end);
		
		log.info(String.format(result, map.get("shzs"), map.get("szzs")));
		return result;
	}
	
//	public void printDetail(String dm)
//	{
//		mapper.select01(dm);
//		
//	}
	
//	select sum(tcap)/sum(mfratio2) from stck11 where rq='2020-10-21' and dm in( select dm from stck01 where hy02='007000');
//	select dm,tcap,mfratio2 from stck11 where rq='2020-10-21' and dm in( select dm from stck01 where hy02='004000') order by mfratio2;
	
	/**
	 * 获取行业市盈率,市值/净利润
	 * @param hy
	 * @param rq
	 */
	public void getPE(String hy, String rq)
	{//
//		countHyPe
	}
	
	public void savecsv(List<StockModel> lst, String name)
	{
		try {
			FileOutputStream fos = new FileOutputStream("D:/program/Python37/test/" + name + ".csv");
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
	        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("代码", "名称", "跌幅(%)", "所属行业", "当前价格", "总市值(万元)", "备注");
	        CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);

	        for (StockModel sm : lst)
	        {
	        	Stock11Model s11 = sm.getStock11();
	        	
	        	StringBuffer result = new StringBuffer();
	        	for (Stock12Model s12 : sm.getLst())
	    		{
	    			result.append(s12.getRq());
	    			result.append("净利润:");
	    			result.append(s12.getJlr());
//	    			result.append("市盈率():");
//	    			result.append(s11.getTcap().divide(s12.getJlr().multiply(new BigDecimal(10000)), 1, BigDecimal.ROUND_HALF_DOWN));
	    		}
	        	
//	        	csvPrinter.printRecord(s11.getDm(), sm.getNm(), sm.getPercent(), sm.getHynm(), 
//	        			s11.getPrice(), s11.getTcap().divide(new BigDecimal(10000)), result.toString());
	        }

	        csvPrinter.flush();
	        csvPrinter.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        

	}
	
	/**
	 * 使用 Map按value进行排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, BigDecimal> sortMapByValue(Map<String, BigDecimal> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		Map<String, BigDecimal> sortedMap = new LinkedHashMap<String, BigDecimal>();
		List<Map.Entry<String, BigDecimal>> entryList = new ArrayList<Map.Entry<String, BigDecimal>>(oriMap.entrySet());
		Collections.sort(entryList, new MapValueComparator());

		Iterator<Map.Entry<String, BigDecimal>> iter = entryList.iterator();
		Map.Entry<String, BigDecimal> tmpEntry = null;
		while (iter.hasNext()) {
			tmpEntry = iter.next();
			sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}
		return sortedMap;
	}

}
